package com.itheima.service.impl;

import com.itheima.mapper.CategoryMapper;

import com.itheima.pojo.Category;
import com.itheima.service.CategoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


@RequiredArgsConstructor
@Service
public class CategoryServiceImpl implements CategoryService {

    private final CategoryMapper categoryMapper;


    @Override
    public List<Category> list() {
        //查询所有分类数据
        List<Category> categoryList = categoryMapper.list();

        //找到所有顶级分类  filter:对stream流进行筛选  .collect是终结方法 （）里面的写法是转成字符串
        List<Category> parents = categoryList.stream().filter(c -> c.getParentId() == 0).collect(Collectors.toList());

        //找到所有非顶级分类
        List<Category> children = categoryList.stream().filter(c -> c.getParentId() > 0).collect(Collectors.toList());

        //调用下面的方法进行查找
        parents.forEach(c->{
            findChildren(c,children);
        });
        return parents;

    }


    /**
     * 递归查找子分类的方法
     */
    public void findChildren(Category category,List<Category> children){
        //创建一个集合，用于储存子分类
        List<Category> currentChildren = new ArrayList<>();
        //循环所有子分类 //判断查找当前类的子分类
        List<Category> list = children.stream().filter(c -> Objects.equals(c.getParentId(), category.getId())).toList();


        //如果没有子分类则结束  有则继续
        if(!CollectionUtils.isEmpty(list)){
            list.forEach(c->findChildren(c,children));
        }
        //将查找结果赋值给当前类的子分类属性children
        category.setChildren(list);
    }
}
